package com.huanying.sales.region;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huanying.framework.BaseController;

@Controller
public class RegionController extends BaseController {

	@Autowired  
	private RegionService regionService;
	
	Logger logger = Logger.getLogger(RegionController.class);
	
	@RequestMapping("/show_add_region.do")
	public String show_add(String id, String project_id,Model model) throws Exception {
		List regions;
		int pro_id = Integer.valueOf(project_id);
		regions = regionService.getByPorjectId(pro_id);
		
		model.addAttribute("regions", regions);
		model.addAttribute("project_id", project_id);
		return "sales/region/add_region";
	}
	
	@RequestMapping(value = "/add_region.do", method = RequestMethod.POST)
	@ResponseBody 
	public Map<String, String> add(@RequestBody Region region) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		try {
			if(region.getId()==0){
				regionService.add(region);
			}
			else{
				regionService.update(region);
			}
			map.put("flag", "1");
		} catch (Exception e) {
			logger.error("操作分区失败",e);
			map.put("flag", "0");
		}
		
		return map;
	}
	
	@RequestMapping(value = "/delete_region.do", method = RequestMethod.POST)
	@ResponseBody 
	public Map<String, String> delete(@RequestBody Region region) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		try {
			if(region.getId()!=0){
				region.setStatus(0);
				int i = regionService.delete(region);
				if(i>0){
					map.put("flag", "1");
				}
				else{
					map.put("flag", "2");
				}
			}
			else{
				map.put("flag", "2");  //未发现需要删除数据
			}
		} catch (Exception e) {
			logger.error("操作分区失败",e);
			map.put("flag", "0");
		}
		return map;
	}
}
